﻿#include "SelectDatatDialog.h"
#include "ui_SelectDatatDialog.h"
#include <QIcon>
#include <QLabel.h>
#include <QVBoxLayout>
#include <QComboBox.h>
#include <QScrollArea.h>
#include <QListView.h>
#include <QStandardItemModel.h>
#include "BaseModule/IBaseSignal.h"
#include "BaseModule/GlobalHelper.h"
#include "BaseWidget/IdaWidgetHelper.h"
#include "BaseWidget/IdaDialogMsg.h"
#include "Curve2DKeySelcetBar.h"

#include <iostream>

namespace pst
{
    SelectDatatDialog::SelectDatatDialog(QWidget* parent)
        : IdaDialogFrame(parent), m_variableAxisValue{ nullptr }, m_keySelectBarList{}, m_valueSelectBar{ nullptr }, m_ui(new Ui::SelectDatatDialog())
    {
        m_ui->setupUi(this);
        setWindowTitle(QStringLiteral("选择数据"));
        setWindowIcon(QIcon(":/include/Image/Moon.jpg"));
        // this->setIsFixedSize(true);
        setContentsMargins(0, 0, 0, 0);
        // this->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
        setWindowModality(Qt::ApplicationModal);
        // setWindowModality(Qt::ApplicationModal);//设置为模态，点击其他控件不响应
        // setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
        m_ui->scrollArea->setStyleSheet("QScrollArea { border: none; }");
    }

    SelectDatatDialog::~SelectDatatDialog()
    {
        delete m_ui;
    }

    void SelectDatatDialog::setDialogTitle(const QString& title)
    {
        setWindowTitle(title);
    }

    QString SelectDatatDialog::getDialogTitle() const
    {
        return windowTitle();
    }

    void SelectDatatDialog::setKeyDataList(
        const QList<QPair<QString, QVector<double>>>& dataList)
    {
        m_keyDataList = dataList;
    }

    QList<QPair<QString, QVector<double>>>
        SelectDatatDialog::getkeyDataList() const
    {
        return m_keyDataList;
    }

    void SelectDatatDialog::setValueDataList(
        const QList<QString>& dataList)
    {
        m_valueNameList = dataList;
    }

    QList<QString> SelectDatatDialog::getValueDataList() const
    {
        return m_valueNameList;
    }

    void SelectDatatDialog::updateUI()
    {
        switch (m_2DPlotType)
            {
        case FileDataType::File2DCurve:
                setWindowTitle(QStringLiteral("二维折线图"));
                break;
        case FileDataType::FilePolar:
                setWindowTitle(QStringLiteral("极坐标图"));
                break;
        case FileDataType::FileTwoDHeatMap:
                setWindowTitle(QStringLiteral("二维热力图"));
                break;
            default:
                break;
            }
        // auto _page1Layout = new QVBoxLayout(this);

        // 变量区域
        // auto variableArea = new QScrollArea(this);
        // auto variableAreaLayout = new QHBoxLayout(variableArea);
        // QLabel* listText = new QLabel("变量", this);
        // listText->setTe xtPixelSize(12);
        // m_variableAxisValue = new QComboBox(this);
        // variableAreaLayout->addWidget(listText);
        // variableAreaLayout->addWidget(m_variableAxisValue);
        if (m_isHeatMap)
        {
            m_ui->label_listText->setText(QStringLiteral("横轴变量:"));
            // QLabel* yText = new QLabel(tr("y变量"), this);
            // variableAreaLayout->addWidget(yText);
            // m_secondVariable = new QComboBox(this);
            // variableAreaLayout->addWidget(m_secondVariable);
            m_ui->label_yText->setText(QStringLiteral("纵轴变量"));
            m_ui->label_yText->show();
            m_ui->comboBox_secondVariable->show();
        }
        else
        {
            m_ui->label_listText->setText(QStringLiteral("变量:"));
            m_ui->label_yText->hide();
            m_ui->comboBox_secondVariable->hide();
        }
        //_page1Layout->addWidget(variableArea);

        // QWidget* _otherKeyWidget = new QWidget(this);
        ////otherKey->setMaximumWidth(_contentWidth);
        //_otherKeyWidget->setStyleSheet("background:transparent;");
        //
        // QScrollArea* otherKeyArea = new QScrollArea(this);
        // otherKeyArea->setWidget(_otherKeyWidget);
        // otherKeyArea->setWidgetResizable(true);
        ////otherKeyArea->setFixedHeight(100);
        // otherKeyArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        // otherKeyArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        // auto otherKeyAreaAreaLayout = new QVBoxLayout(_otherKeyWidget);
        int index = 0;
        for (const auto& i : m_keyDataList)
        {
            // 不是多文件同时选择绘制图形
            if (m_optionalKeyList.isEmpty())
            {
                // 变量区
                m_ui->comboBox_variableAxisValue->addItem(i.first);
            }
            // 处于交集key列表中
            else if (m_optionalKeyList.contains(i.first.toLower()))
            {
                // 变量区
                m_ui->comboBox_variableAxisValue->addItem(i.first);
                m_indexMapping.append(index); // 索引映射
            }
            if (m_isHeatMap)
            {
                m_ui->comboBox_secondVariable->addItem(i.first);
            }
            ++index;
            // 其他值区域
            auto cur = new Curve2DKeySelcetBar(this);
            cur->setData(i.first, i.second.toList());
            if (m_2DPlotType == FileDataType::FileTwoDHeatMap)
                cur->setMultipleSelected(false);
            else
                cur->setMultipleSelected(true);
            m_ui->otherKeyAreaAreaLayout->addWidget(cur);
            m_keySelectBarList.push_back(cur);
        }
        // m_ui->otherKeyAreaAreaLayout->addStretch();
        //_page1Layout->addWidget(otherKeyArea);

        // 其他参数--> value
        // QWidget* _valueWidget = new QWidget(this);
        ////otherKey->setMaximumWidth(_contentWidth);
        //_valueWidget->setStyleSheet("background:transparent;");
        // QScrollArea* valueyArea = new QScrollArea(this);
        // valueyArea->setWidget(_valueWidget);
        // valueyArea->setWidgetResizable(true);
        ////otherKeyArea->setFixedHeight(100);
        // valueyArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        // valueyArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        // auto valueAreaAreaLayout = new QVBoxLayout(valueyArea);
        //_page1Layout->addWidget(valueyArea);

        m_valueSelectBar = new Curve2DKeySelcetBar(this);
        m_valueSelectBar->setData("结果数据:", m_valueNameList);
        m_ui->verticalLayout_ResultData->addWidget(m_valueSelectBar);
        if (m_2DPlotType == FileDataType::FileTwoDHeatMap)
        {
            m_valueSelectBar-> setMultipleSelected(false);
        }
        /// 步骤很重要，先设置m_variableAxisValue的值，再连信号，再设置currentIndex
        connect(m_ui->comboBox_variableAxisValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SelectDatatDialog::slot_variableIndexChanged);
        if (m_isHeatMap)
        {
            connect(m_ui->comboBox_secondVariable, QOverload<int>::of(&QComboBox::currentIndexChanged),
                [this](int index)
                {
                    int varIndex = m_ui->comboBox_variableAxisValue->currentIndex();
                    if (!m_indexMapping.isEmpty())
                    {
                        varIndex = m_indexMapping.at(varIndex);
                    }
                    for (int i = 0; i < m_keySelectBarList.size(); ++i)
                    {
                        ((i == varIndex) || (i == index)) ? m_keySelectBarList.at(i)->hide() : m_keySelectBarList.at(i)->show();
                    }
                });
        }
        if (!m_keyDataList.empty())
        {
            m_ui->comboBox_variableAxisValue->setCurrentIndex(0);
            int tmpIndex = 0;
            if (!m_indexMapping.isEmpty())
            {
                tmpIndex = m_indexMapping.at(tmpIndex);
            }
            m_keySelectBarList.at(tmpIndex)->hide();
            m_oldVariableIndex = tmpIndex;
            if (m_isHeatMap)
            {
                auto* view = qobject_cast<QListView*>(m_ui->comboBox_secondVariable->view());
                auto* model = qobject_cast<QStandardItemModel*>(m_ui->comboBox_secondVariable->model());
                auto* item = model->item(tmpIndex);
                view->setRowHidden(tmpIndex, true);
                item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
                int secondIndex = tmpIndex == 1 ? 0 : 1;
                m_ui->comboBox_secondVariable->setCurrentIndex(secondIndex);
                m_keySelectBarList.at(secondIndex)->hide();
            }
        }
        // if (!m_valueDataList.empty())
        //{
        //     m_valueSelectBar->hide();
        // }
        //_page1Layout->addStretch();

        // auto _cancelOKLayout = new QHBoxLayout();
        // QPushButton* cancelButton = new QPushButton(this);
        // QPushButton* okButton = new QPushButton(this);
        // cancelButton->setText("取消");
        // okButton->setText("确定");
        //_cancelOKLayout->addStretch();
        //_cancelOKLayout->addWidget(cancelButton);
        //_cancelOKLayout->addWidget(okButton);
        //_page1Layout->addLayout(_cancelOKLayout);

        // connect(cancelButton, &QPushButton::clicked, this, &SelectDatatDialog::reject);
        // connect(okButton, &QPushButton::clicked, this, &SelectDatatDialog::accept);
        IdaWidgetHelperInstance->setMainButtonStyle(m_ui->pushButton_accept);
        connect(m_ui->pushButton_reject, &QPushButton::clicked, this, &SelectDatatDialog::reject);

        connect(m_ui->pushButton_accept, &QPushButton::clicked, this, &SelectDatatDialog::accept);
    }

    void SelectDatatDialog::reject()
    {
        IdaDialogFrame::reject();
    }

    void SelectDatatDialog::accept()
    {
        bool _isExistEmptyValue = false;
        int _emptyValueSelectBarIndex = 0;
        auto variableIndex = m_ui->comboBox_variableAxisValue->currentIndex();
        if (!m_indexMapping.isEmpty())
        {
            variableIndex = m_indexMapping.at(variableIndex);
        }
        QList<QPair<int, QList<int>>> chosenkeyList;
        if (m_isHeatMap)
        {
            chosenkeyList.append(qMakePair(m_ui->comboBox_secondVariable->currentIndex(), QList<int>({ 1 })));
        }
        for (int i = 0; i < m_keySelectBarList.size(); ++i)
        {
            if (i == variableIndex)
                continue;
            if (m_isHeatMap && (i == m_ui->comboBox_secondVariable->currentIndex()))
            {
                continue;
            }
            auto indexs = m_keySelectBarList.at(i)->getSelectedIndex();
            if (indexs.size() < 1)
            {
                _emptyValueSelectBarIndex = i;
                _isExistEmptyValue = true;
                break;
            }
            chosenkeyList.append(qMakePair(i, indexs));
        }
        if (_isExistEmptyValue)//数据未选择，弹窗报错
        {            
            auto _emptyValueSelectBar = m_keySelectBarList.at(_emptyValueSelectBarIndex);
            auto _labelText = _emptyValueSelectBar->getLabelText();
            QString _warningText= QString("\"%1\"参数未设置！").arg(_labelText);
            auto _res = IdaDialogMsg::showDialog(nullptr, _warningText, EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
            _emptyValueSelectBar->setPushButtonSelcetBarSelectState(true, Qt::red);
            return;
        }
        auto valueIndexs = m_valueSelectBar->getSelectedIndex();
        if (valueIndexs.size() < 1)
        {
            _isExistEmptyValue = true;
        }
        if (_isExistEmptyValue)//数据未选择，弹窗报错
        {
            auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("\"结果数据\"参数未设置！"), EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
            m_valueSelectBar->setPushButtonSelcetBarSelectState(true, Qt::red);
            return;
        }
        IdaDialogFrame::hideWindow();

        auto _valueIndexsStr = GlobalHelperInstance->convertIntListToQString(valueIndexs);
        auto _chosenkeyListStr = GlobalHelperInstance->convertPairIntIntListToQString(chosenkeyList);
        auto _selectParserIndex = GlobalHelperInstance->convertIntListToQString(m_selectParserIndex);
        QStringList _pyCodes{};
        _pyCodes += QString("twodlinechart = PostProcessing.TwoDLineChart()");       
        _pyCodes += QString("twodlinechart.setLineChartType(%1)").arg((int)m_2DPlotType);
        _pyCodes += QString("twodlinechart.setVariableIndex(%1)").arg(variableIndex);
        _pyCodes += QString("twodlinechart.setChosenkeyList('%1')").arg(_chosenkeyListStr);
        _pyCodes += QString("twodlinechart.setValueIndexs('%1')").arg(_valueIndexsStr);
        _pyCodes += QString("twodlinechart.setSelectParserIndex('%1')").arg(_selectParserIndex);
        _pyCodes += QString("twodlinechart.setIsOpenNewWindow(%1)").arg(m_isOpenNewWindow);
        _pyCodes += QString("twodlinechart.create()");
        emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);
        bool _success{false};//无实际作用
        emit IBaseSignalInstance->signal_set2DPlotType(int(m_2DPlotType));
        emit IBaseSignalInstance->signal_sendSelectedInfo(variableIndex, chosenkeyList, valueIndexs, &_success, m_selectParserIndex, m_isOpenNewWindow);
        // this->close();
        IdaDialogFrame::accept();
    }

    void SelectDatatDialog::slot_variableIndexChanged(int index)
    {
        if (!m_indexMapping.isEmpty())
        {
            index = m_indexMapping.at(index);
        }
        if (m_isHeatMap)
        {
            auto* view = qobject_cast<QListView*>(m_ui->comboBox_secondVariable->view());
            auto* model = qobject_cast<QStandardItemModel*>(m_ui->comboBox_secondVariable->model());
            auto* item = model->item(m_oldVariableIndex);
            view->setRowHidden(m_oldVariableIndex, false);
            item->setFlags(item->flags() | Qt::ItemIsEnabled);
            item = model->item(index);
            view->setRowHidden(index, true);
            item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
            if (index == m_ui->comboBox_secondVariable->currentIndex())
            {
                m_ui->comboBox_secondVariable->setCurrentIndex(m_oldVariableIndex);
            }
        }
        for (int i = 0; i < m_keySelectBarList.size(); ++i)
        {
            i == index ? m_keySelectBarList.at(i)->hide() : m_keySelectBarList.at(i)->show();
            if (m_isHeatMap && (i == m_ui->comboBox_secondVariable->currentIndex()))
            {
                m_keySelectBarList.at(i)->hide();
            }
        }
        m_oldVariableIndex = index;
    }

    // void pst::SelectDatatDialog::slot_sendChosenInfo()
    //{
    //     auto variableIndex = m_variableAxisValue->currentIndex();
    //     if (!m_indexMapping.isEmpty()) {
    //         variableIndex = m_indexMapping.at(variableIndex);
    //     }
    //     QList<QPair<int, QList<int>>> chosenkeyList;
    //     if (m_isHeatMap) {
    //         chosenkeyList.append(qMakePair(m_secondVariable->currentIndex(), QList<int>()));
    //     }
    //     for (int i = 0; i < m_keySelectBarList.size(); ++i)
    //     {
    //         if (i == variableIndex) continue;
    //         if (m_isHeatMap && (i == m_secondVariable->currentIndex())) {
    //             continue;
    //         }
    //         auto indexs = m_keySelectBarList.at(i)->getSelectedIndex();
    //         chosenkeyList.append(qMakePair(i, indexs));
    //     }
    //     auto valueIndexs = m_valueSelectBar->getSelectedIndex();
    //     this->close();
    //     emit signal_sendSelectedInfo(variableIndex, chosenkeyList, valueIndexs);
    // }
} // namespace pst
